package com.puff.web.mvc.own;

import java.util.HashMap;
import java.util.Map;

import com.puff.core.Puff;
import com.puff.framework.Charsets;
import com.puff.framework.annotation.BeanScope;
import com.puff.framework.annotation.Controller;
import com.puff.framework.annotation.Request;
import com.puff.framework.utils.FileUtil;
import com.puff.framework.utils.PathUtil;
import com.puff.framework.utils.StringUtil;
import com.puff.plugin.cache.CacheClient;
import com.puff.web.mvc.PuffContext;
import com.puff.web.view.View;

@Controller(value = "/puff/owm/cache", scope = BeanScope.SINGLETON, report = false)
public class FlushCacheController {
	private static String content;
	static {
		content = FileUtil.toString(Charsets.UTF_8, PathUtil.fromJar("resource/owm/cache-flush"));
	}

	@Request.GET
	public View index() {
		if (!MonitorInfo.isLogin()) {
			return MonitorInfo.login("cache-flush");
		} else {
			String htmlContent = content.replace("${ctx}", Puff.getContextPath());
			return View.html(htmlContent);
		}
	}

	@Request.POST
	public View flush() {
		if (!MonitorInfo.isLogin()) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("msg", "0000");
			map.put("target", Puff.getContextPath() + "/puff/owm/cache");
			return View.json(map);
		} else {
			String cacheName = PuffContext.getParameter("cacheName");
			String cacheKey = PuffContext.getParameter("cacheKey");
			if (StringUtil.empty(cacheName)) {
				return View.json("msg", "CacheName can not be null ! ");
			}
			if (StringUtil.empty(cacheKey)) {
				return View.json("msg", "CacheKey can not be null ! ");
			}
			CacheClient client = CacheClient.getCacheClient();
			if ("*".equals(cacheKey)) {
				client.clear(cacheName);
			} else {
				client.remove(cacheName, cacheKey);
			}
			return View.json("msg", "Flush success ! ");
		}
	}
}